namespace Dan.Common.Extend
{
    public static class NumberExtend
    {
        /// <summary>
        /// string型转换为byte型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的byte类型结果</returns>
        public static byte StrToByte(this string str, byte def = 0)
        {
            if (!byte.TryParse(str, out byte result))
            {
                return def;
            }
            return result;
        }

        /// <summary>
        /// string型转换为ushort型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的ushort类型结果</returns>
        public static ushort StrToUShort(this string str, ushort def)
        {
            if (!ushort.TryParse(str, out ushort result))
            {
                return def;
            }
            return result;
        }

        /// <summary>
        /// string型转换为int型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StrToInt(this string str, int def = 0)
        {
            if (!int.TryParse(str, out int result))
            {
                return def;
            }
            return result;
        }

        /// <summary>
        /// string型转换为uint型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的uint类型结果</returns>
        public static uint StrToUInt(this string str, uint def = 0)
        {
            if (!uint.TryParse(str, out uint result))
            {
                return def;
            }
            return result;
        }

        /// <summary>
        /// string型转换为float型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的float类型结果</returns>
        public static float StrToFloat(this string str, float def = 0)
        {
            if (!float.TryParse(str, out float result))
            {
                return def;
            }
            return result;
        }
        public static double StrToDouble(this string str, double def = 0)
        {
            if (!double.TryParse(str, out double result))
            {
                return def;
            }
            return result;
        }

        /// <summary>
        /// string型转换为decimal型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的decimal类型结果</returns>
        public static decimal StrToDecimal(this string str, decimal def = 0)
        {
            if (!decimal.TryParse(str, out decimal result))
            {
                return def;
            }
            return result;
        }
    }
}